global parity
global G
global H
global errTable
global n, 
global k
global n_k;

n = 7;
k = 4;
n_k = 3;
pol = [1 0 1 1];
[H, G] = cyclgen(7, pol);

H = H';
errTable = syndtable(H');

function c = linearEncode(m)
  global G;
  c = modulo(m*G,2);
endfunction

function m = linearDecode(c)
  global H, errTable, k;
  len = size(c,1)
  m = zeros(len , k)
  for j = 1:len
    row = c(j, :);
    s = modulo(row * H,2);
    err = errTable(bi2de(fliplr(s))+1, :);
    row = modulo(err + row,2)
    m(j, :) = row(1:k);
  end
endfunction

totalBlock = 1000000;
totalBits = totalBlock*k; 
once = 1000;
codeBERs = logspace(-1,-5,9);
//codeBERs = [0.01]
msgBitErr = zeros(codeBERs);
msgBERs = zeros(codeBERs);

for j = 1:length(codeBERs)
  ber = codeBERs(j)
  for i = 1:totalBlock/once
    msg = round(rand(once,k));
    code = linearEncode(msg);
    rcv_code = fixErrRate(code, ber);
    rcv_msg = linearDecode(rcv_code);
    msgBitErr(j) = msgBitErr(j) + length(find(rcv_msg ~= msg));
  end
end
msgBERs = msgBitErr./totalBits
